package reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * 通过反射机制访问属性
 */
public class ReflectDemo8 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        Class cls = Class.forName("reflect.Person");
        Constructor c = cls.getConstructor();
        Object obj = c.newInstance();

        Field filed  = cls.getDeclaredField("name");
        filed.setAccessible(true);
        filed.set(obj,"张三");
        System.out.println("姓名："+filed.get(obj));
        filed.setAccessible(false);

        Field field1 = cls.getDeclaredField("age");
        filed.setAccessible(true);
        filed.set(obj,25);
        System.out.println("年龄:"+filed.get(obj));
        filed.setAccessible(false);

        System.out.println(obj);

    }
}
